<template>
  <div class="p-3">
    <a-card style="height: 820px" :bordered="false">
      <div class="mb-4 flex items-center justify-between">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="修改时间">
            <a-range-picker v-model:value="searchForm.time" />
          </a-form-item>
          <a-form-item label="所属项目">
            <a-tree-select
              v-model:value="searchForm.comId"
              tree-node-filter-prop="label"
              style="width: 260px"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="comanyList"
              placeholder="请选择所属项目"
            />
          </a-form-item>
          <a-form-item label="扎帐开关">
            <a-select v-model:value="searchForm.switchs" placeholder="请选择">
              <a-select-option :value="0">开</a-select-option>
              <a-select-option :value="1">关</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="修改人">
            <a-tree-select
              v-model:value="searchForm.operator"
              tree-data-simple-mode
              allow-clear
              style="width: 150px"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="selectList"
              placeholder="请选择操作人"
              :load-data="onLoadData"
            />
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              class="mr-3"
              :icon="h(SearchOutlined)"
              @click="onSearch"
              >查询</a-button
            >
          </a-form-item>
        </a-form>
        <a-button type="primary" @click="showModal"> 新增 </a-button>
      </div>
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        class="mt-3"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex == 'switchs'">
            <template v-if="record.switchs == 0"> 开 </template>
            <template v-if="record.switchs == 1"> 关 </template>
          </template>
          <template v-if="column.dataIndex == 'action'">
            <a-button type="link" @click="handleEdit(record)">编辑</a-button>
            <a-popconfirm
              placement="bottom"
              ok-text="是"
              cancel-text="否"
              title="确认删除吗？"
              @confirm="handleDelete(record)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>
    <!-- 新增/编辑参数弹窗 -->
    <a-modal
      :visible="modalVisible"
      :title="isEdit ? '编辑参数' : '新增参数'"
      @ok="handleOk"
      @cancel="handleCancel"
      width="300px"
    >
      <a-form :model="formData">
        <a-form-item label="归属机构">
          <a-tree-select
            v-model:value="formData.comId"
            tree-node-filter-prop="label"
            style="width: 160px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="comanyList"
            placeholder="请选择所属项目"
          />
        </a-form-item>
        <a-form-item label="扎帐开关">
          <a-select
            v-model:value="formData.switchs"
            placeholder="请选择"
            style="width: 160px"
          >
            <a-select-option :value="0">开</a-select-option>
            <a-select-option :value="1">关</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, h, onMounted } from 'vue';
import { SearchOutlined } from '@ant-design/icons-vue';
import {
  getParameterPriorityInfo,
  addParameterPriorityInfo,
  editParameterPriorityInfo,
  delParameterPriorityInfo,
} from '#/api/core/setting';
import { getOperatorApi } from '#/api/core/statistical';
import { getCompanyTree } from '#/api/core/develop';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

onMounted(() => {
  getList();
  getTableData();
});
const searchForm = reactive({
  time: '',
  comId: undefined,
  operator: '',
  switchs: undefined,
});
interface CompanyTreeNode {
  key: string | number;
  label: string;
  value: string | number;
  isLeaf: boolean;
  children?: CompanyTreeNode[];
}

const comanyList = ref<CompanyTreeNode[]>([]);
const selectList = ref<OperatorNode[]>([]);
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): any[] => {
      // console.log(tree)
      return tree.map((item: any) => {
        const processedItem = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData || [];
    // console.log(comanyList.value);
  });
};
const getList = () => {
  getOperatorApi(null)
    .then((res: any) => {
      // console.log(res);
      selectList.value = (res || []).map((item: any) => {
        return {
          id: item.id,
          value: item.id,
          title: item.name,
          key: item.id,
          isLeaf: !!item.userId, // 如果有userId说明是叶子节点
        };
      });
    })
    .catch((error) => {
      console.error('获取操作人员列表失败:', error);
      message.error('获取操作人员列表失败');
    });
};
const onLoadData = (treeNode: any) => {
  return new Promise((resolve) => {
    // console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getOperatorApi(treeNode.id)
      .then((res: any) => {
        const children = res.map((item: any) => {
          // console.log(item);
          return {
            id: item.userId ? item.userId : item.id,
            value: item.name ? item.name : item.name,
            title: item.name,
            key: item.userId ? item.userId : item.id,
            isLeaf: !!item.userId, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          for (let node of nodes) {
            if (node.key === treeNode.id) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(selectList.value);
        selectList.value = [...selectList.value];
        // console.log(selectList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error('加载子节点失败:', error);
        message.error('加载子节点失败');
        resolve(undefined);
      });
  });
};
interface OperatorNode {
  id: string | number;
  value: string | number;
  title: string;
  key: string | number;
  isLeaf: boolean;
  children?: OperatorNode[];
}

// 弹窗显示状态
const modalVisible = ref(false);
// 是否为编辑状态
const isEdit = ref(false);
// 当前编辑的记录ID
const currentEditId = ref('');

// 表单数据
const formData = reactive({
  comId: '',
  switchs: '',
});

// 表格数据
const dataSource = ref<TableRecord[]>([]);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});

// 显示弹窗
const showModal = (edit = false, record = null) => {
  isEdit.value = edit;
  modalVisible.value = true;

  if (edit && record) {
    // 编辑模式，填充表单数据
    currentEditId.value = record.id;
    Object.assign(formData, {
      comId: record.comId,
      switchs: record.switchs,
    });
  } else {
    // 新增模式，重置表单数据
    currentEditId.value = '';
    Object.assign(formData, {
      comId: '',
      switchs: '',
    });
  }
};

// 定义表格行数据接口
interface TableRecord {
  id: string | number;
  comId: string | number;
  comName: string;
  switchs: number;
  operator: string;
  changeTime: string;
  [key: string]: any;
}

// 处理编辑操作
const handleEdit = (record: TableRecord) => {
  showModal(true, record);
};

// 确认提交
const handleOk = () => {
  if (!formData.comId) {
    message.warning('请选择归属机构');
    return;
  }
  if (formData.switchs === '') {
    message.warning('请选择扎帐开关');
    return;
  }

  const params = {
    comId: formData.comId,
    switchs: formData.switchs,
  };

  if (isEdit.value) {
    // 编辑模式
    editParameterPriorityInfo({
      ...params,
      id: currentEditId.value,
    })
      .then(() => {
        message.success('编辑成功');
        modalVisible.value = false;
        onSearch(); // 刷新表格数据
      })
      .catch((error) => {
        console.error('编辑失败:', error);
        message.error('编辑失败');
      });
  } else {
    // 新增模式
    addParameterPriorityInfo(params)
      .then(() => {
        message.success('添加成功');
        modalVisible.value = false;
        onSearch(); // 刷新表格数据
      })
      .catch((error) => {
        console.error('添加失败:', error);
        message.error('添加失败');
      });
  }
};

// 取消
const handleCancel = () => {
  modalVisible.value = false;
  isEdit.value = false;
  currentEditId.value = '';
  // 重置表单数据
  Object.assign(formData, {
    comId: '',
    switchs: '',
  });
};

const columns = [
  {
    title: '归属机构',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
  },
  {
    title: '扎帐开关',
    dataIndex: 'switchs',
    key: 'switchs',
    align: 'center',
  },
  {
    title: '修改人',
    dataIndex: 'operator',
    key: 'operator',
    align: 'center',
  },
  {
    title: '修改时间',
    dataIndex: 'changeTime',
    key: 'changeTime',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'center',
  },
];
const onSearch = () => {
  interface QueryParams {
    pageNo: number;
    pageSize: number;
    comId: string | number;
    time: string;
    operator: string | number;
    switchs: string | number;
  }
  const query: QueryParams = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    comId: searchForm.comId ?? '',
    switchs: searchForm.switchs ?? '',
    time: searchForm.time
      ? dayjs(searchForm.time[0]).format('YYYY-MM-DD') +
        ',' +
        dayjs(searchForm.time[1]).format('YYYY-MM-DD')
      : '',
    operator: searchForm.operator ?? '',
  };
  getParameterPriorityInfo(query).then((res: any) => {
    console.log(res);
    dataSource.value = res.data.data.data;
    pagination.total = res.data.data.total;
  });
};
const handleDelete = (e: any) => {
  delParameterPriorityInfo(e.id).then((res: any) => {
    console.log(res);
    if(res.data.code==200){
      message.success('删除成功');
      onSearch();
    }else{
      message.error('删除失败')
    }
  });
};
</script>
<style scoped>
.editor-container {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
}

.editor-toolbar {
  padding: 8px 12px;
  border-bottom: 1px solid #d9d9d9;
  background-color: #fafafa;
  display: flex;
  align-items: center;
  gap: 4px;
  border-top-left-radius: 6px;
  border-top-right-radius: 6px;
}

.editor-toolbar .ant-btn {
  padding: 0 6px;
  height: 24px;
  min-width: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.editor-toolbar .ant-btn:hover {
  background-color: #e6f7ff;
}
</style>
